#include "sqlitedbwrapper.h"
#include <string>
#include <cmath>

SqliteDbWrapper::SqliteDbWrapper(sqlite3 *dbConnection)
{
    m_db = dbConnection;
}

std::string SqliteDbWrapper::GetStyleSheet(const char* routeID){
    char idString[64];
    sprintf(idString, "SELECT StyleSheet FROM Line WHERE LineNumber=\"%s\";", routeID);
    sqlite3_prepare_v2(m_db, idString, -1, &m_statement, 0);

    std::string sheet;

    if(sqlite3_step(m_statement) == SQLITE_ROW)
        sheet = (char *) sqlite3_column_text(m_statement, 0);
    else
    {
        std::cout << "Couldn't find stylesheet for route " << routeID << "\n";
        sheet = "default.css";
    }    

    sqlite3_reset(m_statement);
    sqlite3_finalize(m_statement);

    return sheet;
}

int SqliteDbWrapper::QueryStops(const char *sqlString){

    sqlite3_prepare_v2(m_db, sqlString, -1, &m_statement, 0);
    StopData scratch;
    StopVector.clear();

    int orderValue[2] = {0,0};

    if (sqlite3_step(m_statement) == SQLITE_ROW){
        orderValue[0] = orderValue[1] = scratch.order = sqlite3_column_int(m_statement,1);
        scratch.stopName = (char *)sqlite3_column_text(m_statement,0);
        scratch.nextLineIsSecondary = (bool)sqlite3_column_int(m_statement,2);
        scratch.nextLineCaption = (char *)sqlite3_column_text(m_statement,3);
        scratch.correspondances = (char *)sqlite3_column_text(m_statement,4) + QString::fromLatin1(" ");

        while(sqlite3_step(m_statement) == SQLITE_ROW){

            orderValue[0] = sqlite3_column_int(m_statement,1);

            if (orderValue[0] != orderValue[1]){
                StopVector.push_back(scratch);


                scratch.correspondances.clear();
                scratch.stopName = (char *)sqlite3_column_text(m_statement,0);
                scratch.nextLineIsSecondary = (bool)sqlite3_column_int(m_statement,2);
                scratch.nextLineCaption = (char *)sqlite3_column_text(m_statement,3);

                scratch.order = orderValue[1] = orderValue[0];

            }

            scratch.correspondances.append((char *)sqlite3_column_text(m_statement,4) + QString::fromLatin1(" "));
        }

        StopVector.push_back(scratch);

    } else {
        std::cout << "No Results. (Check that line number and database specified at startup)\n";
    }

    //Statement MUST be reset before anothe query is made
    sqlite3_reset(m_statement);
    sqlite3_finalize(m_statement);

    return StopVector.size();

}
